package com.study.lease.web.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.study.lease.common.constant.RedisConstant;
import com.study.lease.common.exception.LeaseException;
import com.study.lease.common.result.ResultCodeEnum;
import com.study.lease.common.utils.CodeUtil;
import com.study.lease.common.utils.JwtUtil;
import com.study.lease.model.entity.UserInfo;
import com.study.lease.model.enums.BaseStatus;
import com.study.lease.web.app.mapper.UserInfoMapper;
import com.study.lease.web.app.service.LoginService;
import com.study.lease.web.app.service.SmsService;
import com.study.lease.web.app.vo.user.LoginVo;
import com.study.lease.web.app.vo.user.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SmsService smsService;

    @Autowired
    private StringRedisTemplate redis;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Override
    public void getCode(String phone) {
        String code = CodeUtil.getCode(6);
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;

        // 判断是否已发送验证码
        Boolean hasKey = redis.hasKey(key);
        if (hasKey){// 如果存在key，则判断是否在60秒内发送过验证码
            Long ttl = redis.getExpire(key, TimeUnit.SECONDS); //ttl为 剩余过期时间
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC-ttl<RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC){
                // 验证码发送频繁
                throw  new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN.getCode(), ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN.getMessage());
            }
        }
        //发送短信验证码
        smsService.sendCode(phone, code);
        //将验证码存入redis中，并设置过期时间
        /**
         * opsForValue().set()方法，第一个参数是key，第二个参数是value，第三个参数是过期时间TTL
         * 用来操作String类型的数据
         */
        redis.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC,TimeUnit.SECONDS);//验证码10分钟过期
    }

    @Override
    public String login(LoginVo loginVo) {
        //1.校验手机号是否为空
        if (loginVo.getPhone()==null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY.getCode(),ResultCodeEnum.APP_LOGIN_PHONE_EMPTY.getMessage());

        }
        //2.校验验证码是否为空
        if (loginVo.getCode()==null){
            throw  new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY.getCode(),ResultCodeEnum.APP_LOGIN_CODE_EMPTY.getMessage());

        }
        //3.校验验证码是否过期
        String key=RedisConstant.APP_LOGIN_PREFIX+loginVo.getPhone();
        String code=redis.opsForValue().get(key);
        if (code==null){
            throw  new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY.getCode(),ResultCodeEnum.APP_LOGIN_CODE_EXPIRED.getMessage());

        }
        //4.校验验证码是否正确
        if (!code.equals(loginVo.getCode())){
            throw  new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR.getCode(),ResultCodeEnum.APP_LOGIN_CODE_ERROR.getMessage());
        }
        //5.判断用户是否存在，不存在则创建用户并登录
        //6.判断用户是否被禁用，禁用则抛出异常
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);//查询用户是否存在
        if (userInfo==null){
            //不存在
            //创建用户
           userInfo=new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("新用户"+loginVo.getPhone().substring(7));
           userInfoMapper.insert(userInfo);
        }else {
            //是否禁用
            if (userInfo.getStatus()==BaseStatus.DISABLE){
                throw  new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR.getCode(),ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR.getMessage());
            }
        }
        return JwtUtil.createToken(userInfo.getId(),userInfo.getPhone());
    }

    @Override
    public UserInfoVo getLoginUserInfoById(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        UserInfoVo userInfoVo = new UserInfoVo(userInfo.getNickname(), userInfo.getAvatarUrl());

        return userInfoVo;
    }
}
